package com.adkun.community.controller;

import com.adkun.community.entity.User;
import com.adkun.community.service.UserService;
import com.adkun.community.util.CommunityConstants;
import com.adkun.community.util.CommunityUtil;
import com.adkun.community.util.MailClient;
import com.adkun.community.util.RedisKeyUtil;
import com.google.code.kaptcha.Producer;
import com.mysql.cj.util.TimeUtil;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController implements CommunityConstants {

    /**
     * 注册与激活
     */

    @Autowired
    private UserService userService;

    // 访问注册页面
    @RequestMapping(path = "/register", method = RequestMethod.GET)
    public String getRegisterPage() {
        return "/site/register";
    }

    @RequestMapping(path = "/register", method = RequestMethod.POST)
    public String register(Model model, User user) {
        Map<String, Object> map = userService.register(user);
        if (map == null || map.isEmpty()) {
            // map是空的时候，注册成功了，跳到/site/operate-result
            model.addAttribute("msg", "注册成功，我们已经向您的邮箱发送了一封激活邮件");
            model.addAttribute("target", "/community/index");
            return "/site/operate-result";
        } else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            model.addAttribute("emailMsg", map.get("emailMsg"));

            return "/site/register";
        }
    }

    @RequestMapping(path = "/activation/{id}/{activationCode}", method = RequestMethod.GET)
    public String activate(Model model, User user) {
        User u = userService.findUserById(user.getId());
        int result = userService.activate(user);
        if (result == ACTIVATION_FAILURE) {
            model.addAttribute("msg", "激活失败，激活码不正确");
            model.addAttribute("target", "/community/index");
        } else if (result == ACTIVATION_SUCCESS) {
            model.addAttribute("msg", "激活成功，即将跳转到登录页");
            model.addAttribute("target", "/community/login");
        } else {
            model.addAttribute("msg", "已激活，请勿重复操作");
            model.addAttribute("target", "/community/index");
        }
        return "/site/operate-result";
    }

    /**
     * 登录
     *
     * @return
     */

    @RequestMapping(path = "/login", method = RequestMethod.GET)
    public String getLoginPage() {
        return "/site/login";
    }

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @RequestMapping(path = "/login", method = RequestMethod.POST)
    public String login(Model model, User user, HttpServletResponse response, /*HttpSession session,*/
                        String code, boolean rememberme,
                        @CookieValue("kaptchaOwner")String kaptchaOwner) {
        // 判断验证码对不对
//        String kaptcha = (String) session.getAttribute("kaptcha");
        // 原：从session取验证码，现：从Redis取验证码
        String kaptcha = null;
        if (StringUtils.isNotBlank(kaptchaOwner)) {
            String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
            kaptcha = (String) redisTemplate.opsForValue().get(redisKey);
        }


        if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) || !kaptcha.equalsIgnoreCase(code)) {
            // 这里使用不区分大小写的比较
            model.addAttribute("codeMsg", "验证码不正确！");
            return "/site/login";
        }

        // 检查帐号、密码（交给业务层处理）
        // 如果勾上“记住我”，存的时间就长一点
        int expiredSeconds = rememberme ? REMEMBER_EXPIRED_SECONDS : DEFAULT_EXPIRED_SECONDS;
        Map<String, Object> map = userService.login(user, expiredSeconds);
        if (map.containsKey("ticket")) {
            // 登录成功
            Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
            cookie.setPath(contextPath);
            cookie.setMaxAge(expiredSeconds);
            response.addCookie(cookie);

            return "redirect:/index"; // 重定向
        } else {
            // 登录失败
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));

            return "/site/login";
        }
    }

    /**
     * 验证码生成
     */

    @Autowired
    private Producer kaptchaProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @RequestMapping(path = "/kaptcha", method = RequestMethod.GET)
    public void getKaptcha(HttpServletResponse response /*HttpSession session*/) throws IOException {
        // 返回的图片，不是String，也不是网页，所以返回值设为void，用response手动添加
        // 生成的验证码要存到服务器，不能用cookie存到浏览器，否则容易被盗取
        String text = kaptchaProducer.createText(); //根据配置，生成一个4位的字符串，范围是数字、大写字母、小写字母
        BufferedImage image = kaptchaProducer.createImage(text);

        //将验证码存入Session
//        session.setAttribute("kaptcha", text);
        // 取代sesson存到Redis
        // 验证码的归属
        String kaptchaOwner = CommunityUtil.generateUUID();
        Cookie cookie = new Cookie("kaptchaOwner", kaptchaOwner);
        cookie.setMaxAge(60);
        cookie.setPath(contextPath);
        response.addCookie(cookie);

        // 验证码存入Redis
        String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
        redisTemplate.opsForValue().set(redisKey, text, 60, TimeUnit.SECONDS); // 设置60秒后失效

        // 将图片直接输出给浏览器
        response.setContentType("image/png"); // 声明给浏览器返回什么类型的数据，这里是图片/png格式

        try {
            OutputStream os = response.getOutputStream(); //获取输出流，这个流不需要手动关闭，由Spring MVC自动管理
            ImageIO.write(image, "png", os); // 使用ImagoIO向浏览器输出图片，(图片,格式，输出流)
        } catch (IOException e) {
            logger.error("响应验证码失败:" + e.getMessage());
        }
    }

    @GetMapping("/logout")
    public String logout(@CookieValue("ticket") String ticket) {
        userService.logout(ticket);
        // 清理Context
        SecurityContextHolder.clearContext();
        return "redirect:/login";
    }




    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;



}
